﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Data;
using IUI;
using System.Data;

namespace BL
{
   public class MainPageController : BaseController<IMainPage>
   {

      public MainPageController(IMainPage page) : base(page) 
      {
          WCF_Client.Instance.Connect();
      }
      
      public override void InitPageEvents()
      {
         _page.Click_AdminButton += btn_Admin_Click;
         _page.Click_Playlists += ShowPlaylists;
         _page.Click_Songs += ShowSongs;
         _page.Click_AddItem += AddItem;
         _page.Click_DeleteItem += DelItem;
         _page.Click_EditItem += EditItem;

         _page.Click_NewSong += NewSong;
      }

      private void btn_Admin_Click(object sender, EventArgs e)
      {
          _page.OpenAdminPage();
      }

      private void ShowPlaylists(object sender, EventArgs e)
      {
          DataTable allLists = WCF_Client.Instance.GetTable(Playlist.TableName);

          List<String> list_to_delete = new List<string>();

          if (null != allLists)
          {
              foreach (var row in allLists.Rows)
              {
                  if ((String)((DataRow)row)["id_user"] != _page.User.Name)
                  {
                      list_to_delete.Add((String)((DataRow)row)["id"]);
                  }
              }              
          }

          DataColumn[] pk = {allLists.Columns["id"]};
          allLists.PrimaryKey = pk;

          foreach (var id in list_to_delete)
          {
              allLists.Rows.Find((String)id).Delete();
          }
          allLists.AcceptChanges();

          _page.Fill_ListOfChoise(allLists);
      }

      private void ShowSongs(object sender, EventArgs e)
      {
          DataTable allSongs = WCF_Client.Instance.GetTable(Song.TableName);

          _page.Fill_ListOfChoise(allSongs);
      }

      private void AddItem(object sender, EventArgs e)
      {
          IPlayFactory factory = null;
          switch (_page.CurrentChoise)
          {
              case "[songs]":
                  factory = new SongFactory();
                  break;
              case "[playlists]":
                  factory = new PlaylistFactory();
                  break;
              default: 
                  break;
          }
          
          _page.AddItem(factory);
      }

      private void DelItem(object sender, EventArgs e)
      {
          _page.DelItem();
      }

      void EditItem(object sender, EventArgs e)
      {
          _page.EditItem();
      }

      void NewSong(object sender, EventArgs e)
      {
          Song s = new Song("New Song", "asdf", "asdf");

          WCF_Client.Instance.SaveSong(s, _page.User);
      }
   }
}

